package de.vocabulary.server.language.translation;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.GZIPInputStream;

import de.vocabulary.shared.model.Vocable;

public class TSVLookup implements TranslationLookup {
	
	public static final String TRANS_PATH = "languageData/translations/";
	public static final String SUFFIX = ".txt.gz";
	
	private Map<String, TranslationProvider> transMap;
	
	public TSVLookup() {
		transMap = new HashMap<String, TranslationProvider>();
	}
	
	@Override
	public Set<String> getTranslation(String term, String sourceLang, String targetLang) throws IOException {
		String transFile = getTransFileName(sourceLang, targetLang);
		
		if (!transMap.containsKey(transFile)) {
			List<Vocable> vocables = getVocablesFromTsvFile(transFile);
			transMap.put(transFile, new TranslationProvider(vocables));
		}
		return transMap.get(transFile).getTranslations(term.toLowerCase());
	}
	
	private String getTransFileName(String lang1, String lang2) {
		if (lang1.compareTo(lang2) < 0) {
			return lang1 + "-" + lang2 + SUFFIX;
		}
		else {
			return lang2 + "-" + lang1 + SUFFIX;
		}
	}
	
	private List<Vocable> getVocablesFromTsvFile(String filename) throws IOException {
		List<Vocable> vocables = new ArrayList<Vocable>();
		
		String path = TRANS_PATH + filename;
		File file = new File(path);
		
		if (!file.exists()) {
			System.out.println("No translations for " + filename + " available.");
			return Collections.emptyList();
		}
		
		BufferedReader br = new BufferedReader(new InputStreamReader(
				new GZIPInputStream(new FileInputStream(file)), "UTF-8"));
		
		String line;
		while ((line = br.readLine()) != null) {
			String[] parts = line.split("\t");
			if (parts.length == 2) {
				String[] translations = parts[1].split(":");
				for (String translation : translations) {
					vocables.add(new Vocable(parts[0].toLowerCase(), translation.toLowerCase()));
				}
			}
		}
		br.close();
		
		System.out.println("read " + vocables.size() + " vocables.");
		
		return vocables;
	}
	
	public String getContentInformation() {
		StringBuilder sb = new StringBuilder();
		for (String key : transMap.keySet()) {
			sb.append(key);
			sb.append("\n");
			sb.append(transMap.get(key));
		}
		return sb.toString();
	}
}
